package com.nf.nf.common.interceptors;

import com.google.gson.Gson;
import com.nf.nf.util.ResourceUtil;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求日志拦截器
 *
 * @author  章隆敏
 * @version  [1.0, 2017年1月6日]
 * @since  [pcloud/2.0]
 */
public class ExceptionInterceptor extends HandlerInterceptorAdapter{
	/** logger */
	protected final static Logger logger = Logger.getLogger(ExceptionInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (ex != null) {
			String msg = "";
			if (ex instanceof NullPointerException) {
				msg = "空指针异常";
			} else if (ex instanceof IOException) {
				msg = "文件读写异常";
			} else {
				msg = ex.toString();
			}
			logger(request, handler, ex);
			response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("success", false);
			result.put("msg", msg);
			writerJson(response, result);
		} else {
			super.afterCompletion(request, response, handler, ex);
		}
	}

	public static void writerJson(HttpServletResponse response, Object object) {
		Gson gson=new Gson();
		response.setContentType("text/html;charset=utf-8");
		writer(response, gson.toJson(object));
	}
	private static void writer(HttpServletResponse response, String str) {
		try {
			// 设置页面不缓存
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = null;
			out = response.getWriter();
			out.print(str);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("error", e);
		}
	}
	/**
	 * 记录日志
	 *
	 * @param request
	 * @param handler
	 * @param ex
	 */
	public void logger(HttpServletRequest request, Object handler, Exception ex) {
		StringBuffer msg = new StringBuffer();
		msg.append("异常拦截日志");
		msg.append("[uri＝").append(request.getRequestURI()).append("]");
		Enumeration<String> enumer = request.getParameterNames();
		while (enumer.hasMoreElements()) {
			String name = (String) enumer.nextElement();
			String[] values = request.getParameterValues(name);
			msg.append("[").append(name).append("=");
			if (values != null) {
				int i = 0;
				for (String value : values) {
					i++;
					msg.append(value);
					if (i < values.length) {
						msg.append("｜");
					}
				}
			}
			msg.append("]");
		}
		logger.error(msg, ex);
	}
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object arg2) throws Exception {

		Map map=request.getParameterMap();
		Gson gson = new Gson();
		String param = gson.toJson(map);
		logger.info("["+ ResourceUtil.getRequestPath(request)+":"+param+"]");
		return true;
	}

}